package com.jnevision.train.controller;


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crtland.landoss.LandOss;
import com.crtland.landoss.Oss;
import com.crtland.landoss.OssInfo;
import com.crtland.landoss.OssType;
import com.crtland.landoss.PathEnum;
import com.crtland.landoss.Result;
import com.google.common.base.Joiner;
import com.jnevision.train.model.Train;
import com.jnevision.train.service.TrainServiceImpl;
import com.jnevision.train.vo.TrainVO;
import com.jnevision.user.model.User;
import com.jnevision.user.service.UserServiceImpl;


/**
 * <p>
 * 培训记录表 前端控制器
 * </p>
 *
 * @author gavin
 * @since 2019-07-23
 */
@RestController
@RequestMapping("/trains")
public class TrainController extends ApiController {

	
	@Autowired
	private TrainServiceImpl trainServiceImpl;
	
	@Autowired
	private UserServiceImpl userServiceImpl;
	
	@Autowired
    private OssInfo ossInfo;
	
    @Autowired
    private StringRedisTemplate redisTemplate;
	
	@PostMapping
    public R<Boolean> add(HttpServletRequest request) {
		
		
		MultipartHttpServletRequest params=((MultipartHttpServletRequest) request);  
        MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");   
        List<MultipartFile> Images = ((MultipartHttpServletRequest) request).getFiles("pic");   
		Train train = new Train();
		
		String title = params.getParameter("title");
		String userName = params.getParameter("userName");
		String createTime = params.getParameter("createTime");
		String trainName = params.getParameter("trainName");

		train.setCreateTime(createTime);
		train.setTitle(title);
		train.setTrainName(trainName);
		train.setUserName(userName);
		
		
    	try {
    		
    		LandOss landOss1 = new LandOss(redisTemplate);
    		Oss oss1 = landOss1.getLandOss(OssType.ALI, ossInfo);
    		Result pdfResult = oss1.upload(PathEnum.MATERIAL, file);
    		if (pdfResult.getStatus()) {
    			train.setFile(pdfResult.getFileUrl());
    		} else {
    			return this.failed("pdf上传失败，请重试");
    		}

			LandOss landOss = new LandOss(redisTemplate);
    		Oss oss = landOss.getLandOss(OssType.ALI, ossInfo);
    		List<Result> result = oss.upload(PathEnum.MATERIAL, Images);
    		
    		List<String> collect = result.stream().map(Result::getFileUrl).collect(Collectors.toList());

    		train.setImg(Joiner.on(",").join(collect));
    		
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
		
        return this.success(this.trainServiceImpl.save(train));
    }

    @PutMapping
    public R<Boolean> update(@RequestBody Train train) {
        return this.success(this.trainServiceImpl.updateById(train));
    }

    @DeleteMapping
    public R<Boolean> delete(Integer id) {
        return this.success(this.trainServiceImpl.removeById(id));
    }

    @GetMapping
    public R<Train> get(Integer id) {
        return this.success(this.trainServiceImpl.getById(id));
    }

    @GetMapping("/page")
    public R<IPage<TrainVO>> page(Page<Train> page, Train train) {
        IPage<Train> pageTrain = this.trainServiceImpl.page(page,
            new QueryWrapper<Train>().like(StringUtils.isNotEmpty(train.getTitle()),"title", train.getTitle()).orderByDesc("create_time"));
        IPage<TrainVO> resultIPage = new Page<TrainVO>(pageTrain.getCurrent(), pageTrain.getSize(), pageTrain.getSize());
        
        List<TrainVO> list = new ArrayList<>();
        
        for (Train t : pageTrain.getRecords()) {
        	TrainVO vo = new TrainVO();
        	BeanUtils.copyProperties(t, vo);
        	if (StringUtils.isNotEmpty(t.getUserId())) {
        		
        		User user = this.userServiceImpl.getById(vo.getUserId());
        		vo.setUserName(user.getName());
        	}
        	if (StringUtils.isNotEmpty(t.getTrainId())) {
        		
        		User byId = this.userServiceImpl.getById(vo.getTrainId());
        		vo.setTrainName(byId.getName());
        	}
			list.add(vo);
		}

        resultIPage.setRecords(list);
        return this.success(resultIPage);
    }
    
    
    
    @GetMapping(value = "/downloads")
    public void download(Integer id, HttpServletResponse response) {
    	Train byId = this.trainServiceImpl.getById(id);

        try {
        	if(byId != null) {
        		
    	        LandOss landOss = new LandOss(redisTemplate);
    	        Oss oss = landOss.getLandOss(OssType.ALI, ossInfo);
    	        InputStream download = oss.download(ossInfo.getBucketName(), "https://cr-property.oss-cn-qingdao.aliyuncs.com/enclosure/2019080500000002.pdf");
    	        System.err.println("download>>>>"+download);
        		IOUtils.copy(download, response.getOutputStream());
        	}
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

